package com.zhugang.week01;

/**
 * @program algorithms
 * @description: palindrome
 * @author: chanzhugang
 * @create: 2022/03/20 22:40
 */
public class PalindromeStr {

    public static void main(String[] args) {
        PalindromeStr palindromeStr = new PalindromeStr();
        String str = "A man, a plan, a canal: Panama";
        boolean flag = palindromeStr.isPalindrome(str);
        System.out.println(flag);

    }

    /**
     * 125.验证回文串
     */
    public boolean isPalindrome(String s) {
        // 不是数字、字母，++， 忽略大小写
        int i = 0;
        int j = s.length() - 1;
        while (i < j) {
            if (!isAlpha(s.charAt(i))) {
                // 遇到非数字和字母跳过
                i++;
                continue;
            }
            if (!isAlpha(s.charAt(j))) {
                j--;
                continue;
            }
            if (toLower(s.charAt(i)) != toLower(s.charAt(j))) {
                return false;
            } else {
                i++;
                j--;
            }
        }
        return true;
    }

    /**
     * 转为小写
     *
     * @param c
     * @return
     */
    private char toLower(char c) {
        if (c >= 'a' && c <= 'z') {
            return c;
        }
        if (c >= 0 && c <= 9) {
            return c;
        }
        return (char) ((int) c + 32);
    }

    /**
     * 判断是不是字符串或者数字
     *
     * @param c
     * @return
     */
    private boolean isAlpha(char c) {
        if (c >= 'a' && c <= 'z') {
            return true;
        }
        if (c >= 'A' && c <= 'Z') {
            return true;
        }
        return c >= '0' && c <= '9';
    }
}